package com.AdvancedDemos.异常;

public class try_catch_finally {
    public static void main(String[] args) {
        try {
            System.out.println("123");
//            return;
//            System.exit(0);//虚拟机停止
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("456");
            //将需要释放资源的代码放入到该语句块中
            //finally中的代码一定会执行,除非虚拟机停止
        }
        System.out.println("789");
        /**
         * 123
         * 456
         * 789
         */


        //面试题
        System.out.println(getSum());//3
        System.out.println(getSum1());//2
    }

    public static int getSum() {
        int num = 1;
        try {
            num++;//num->2
            return num;//暂挂,先执行finally
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            num++;//num->3
            return num;//返回num=3
        }
    }

    public static int getSum1() {
        int num = 1;
        try {
            num += 1;//num->2
            return num;//暂挂,已经记住返回2了,先执行finally
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            num += 1;//num->3,但是不会改变前面return的返回值
        }
        System.out.println("num = " + num);//因为已经return所以压根不执行
        return num;

    }
}
